package com.ibm.iisp.common.file.download;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.inject.Inject;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpStatus;

import com.ibm.iisp.common.file.util.FileStoreUtils;

/**
 * Servlet直接发送本地文件到浏览器下载
 * 
 * @author JohnnyZhou
 *
 */
public class LocaleFileDownloader implements FileDownloader {
	@Inject
	FileStoreUtils fileStoreUtils;
	@Inject
	MessageSource messageSource;

	@Override
	public void download(String path, HttpServletRequest request, HttpServletResponse resp) throws IOException {
		File file = new File(fileStoreUtils.getAbsFilePath(path));
		if (file.exists()) {
			resp.setStatus(HttpStatus.OK.value());
			ServletOutputStream outStream = resp.getOutputStream();
			byte[] buf = new byte[1024 * 50];
			try (FileInputStream fis = new FileInputStream(file)) {
				int len = fis.read(buf);
				while (len > 0) {
					outStream.write(buf, 0, len);
					len = fis.read(buf);
				}
			}
			outStream.flush();
		} else {
			resp.setStatus(HttpStatus.NOT_FOUND.value());
			String errMsg = messageSource.getMessage("msg.fileNotFound", new String[] { path }, LocaleContextHolder.getLocale());
			resp.getWriter().append(errMsg);
		}
	}

}
